package com.subdoc.handler;

import com.subdoc.util.CustomException;
import com.subdoc.util.JsonUtil;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomExceptionResolver implements HandlerExceptionResolver {
    /**
     * Try to resolve the given exception that got thrown during handler execution,
     * returning a {@link ModelAndView} that represents a specific error page if appropriate.
     * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty}
     * to indicate that the exception has been resolved successfully but that no view
     * should be rendered, for instance by setting a status code.
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  the executed handler, or {@code null} if none chosen at the
     *                 time of the exception (for example, if multipart resolution failed)
     * @param ex       the exception that got thrown during handler execution
     * @return a corresponding {@code ModelAndView} to forward to, or {@code null}
     * for default processing
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //handler就是处理器适配器要执行的Handler对象(只有method)
        //解析出异常类型。
        //如果该 异常类型是系统 自定义的异常，直接取出异常信息，在错误页面展示。
        CustomException customException=null;
        if(ex instanceof CustomException){
            customException=(CustomException)ex;

        }else{
            //如果该 异常类型不是系统 自定义的异常，构造一个自定义的异常类型（信息为“未知错误”）。
            customException=new CustomException("未知错误");
        }

        //错误信息
        String message=customException.getMessage();

        //判断是否是ajax请求
        if (request.getHeader("X-Requested-With") != null) {
            try {
                response.getWriter().println(JsonUtil.objectToJson(message));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ModelAndView();
        } else {
            ModelAndView modelAndView=new ModelAndView();

            //将错误信息传到页面
            modelAndView.addObject("message",message);

            //指向到错误界面
            modelAndView.setViewName("error");

            return modelAndView;
        }
    }
}